<?php
/**
 * Created by XM·Tan.
 * Motto: Who shuts love out, in turn shall be shut out from love.
 * Date: 2021/4/24 21:47
 */

namespace app\admin\business;


use app\common\business\BusBase;
use app\common\lib\ArrayLib;
use app\common\model\mysql\SiteLog as SiteLogModel;
use think\facade\Log;
use think\facade\Request;

class SiteLog extends BusBase {

    public $model = null;

    public function __construct() {
        $this->model = new SiteLogModel();
    }

    /**
     * 获取权限列表数据
     * @param $data
     * @param int $limit
     * @param $order
     * @return array
     */
    public function getLists($data, $limit = 10, $order = []) {

        $likeKeys = []; // 如果没有定义这个 有时候会报错
        if (!empty($data)) {
            $likeKeys = array_keys($data);
        }
        try {
            $list = $this->model->getLists($likeKeys, $data, $limit, $order);
            $result = $list->toArray();
        } catch (\Exception $e) {
            Log::error('common-business-SiteLog-getLists: ' . $e->getMessage());
            $result = ArrayLib::getPaginateDefaultData($limit);
        }
        return $result;
    }

    /**
     * 记录日志
     * @param $message 说明
     * @param int $status 状态
     * @return bool
     */
    public function site_log($message, $status = 0) {
        $adminUser = session(config('admin.session_admin'));
        $data = [
            'admin_id'   => $adminUser['id'],
            'username'   => $adminUser['username'],
            'status'     => $status,
            'info'      => "提示语:{$message}",
            'type'       => Request::action(),
            'url'        => Request::url(),
            'operate_ip' => Request::ip(),
            'content'    => json_encode(Request::param()),
        ];
        $this->setSiteLog($data);
    }

    /**
     * 记录操作日志
     * @param $data
     * @return bool|mixed
     */
    public function setSiteLog($data) {
        if (empty($data)) {
            return false;
        }
        try {
            $id = $this->add($data);
            if (!$id) {
                return $id;
            }
            return true;
        } catch (\Exception $e) {
            Log::error('common-business-SiteLog-setSiteLog: ' . $e->getMessage());
        }
    }

    /**
     *  删除一个月前的操作日志
     */
    public function delete() {
        try {
            $this->model->where('create_time', '<= time', time() - (86400 * 30))->delete();
        } catch (\Exception $e) {
            Log::error('common-business-SiteLog-delete: ' . $e->getMessage());
        }
    }

}